﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using mvcForum.Core;

using mvcForum.Web.Controllers;
using mvcForum.Core.Specifications;

using ForumAccessVM = mvcForum.Web.Areas.ForumAPI.ViewModels.ForumAccess;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAPI.Controllers {

	public class ForumAccessController : BaseAPIController {

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Create(ForumAccessVM model, String mode) {
			// TODO: Access
			Core.Forum forum = this.GetRepository<Core.Forum>().Read(model.ForumId);
			Group group = this.GetRepository<Group>().Read(model.GroupId);

			IRepository<ForumAccess> faRepo = this.GetRepository<ForumAccess>();

			ForumAccess fa = faRepo.ReadOne(new ForumAccessSpecifications.SpecificForumAndGroup(forum, group));
			if (fa == null) {
				fa = new ForumAccess();
				fa.Forum = forum;
				fa.Group = group;
				fa.AccessMask = this.GetRepository<AccessMask>().Read(model.AccessMaskId);

				faRepo.Create(fa);
			}
			else {
				fa.AccessMask = this.GetRepository<AccessMask>().Read(model.AccessMaskId);
			}

			this.Context.SaveChanges();

			return this.CustomJson(new { Id = fa.Id });
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Update(ForumAccessVM model, String mode) {
			// TODO: Access
			ForumAccess fa = this.GetRepository<ForumAccess>().Read(model.Id);
			if (fa.Forum.Id == model.ForumId && fa.Group.Id == model.GroupId) {
				fa.AccessMask = this.GetRepository<AccessMask>().Read(model.AccessMaskId);

				this.Context.SaveChanges();
			}

			return new HttpStatusCodeResult(200);
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Delete(Int32 id, String mode) {
			// TODO: Access
			IRepository<ForumAccess> faRepo = this.GetRepository<ForumAccess>();

			ForumAccess fa = faRepo.Read(id);
			if (fa != null) {
				faRepo.Delete(fa);

				this.Context.SaveChanges();
			}

			return new HttpStatusCodeResult(200);
		}

		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult List(Int32 id, String mode) {
			// TODO: Access!!!!
			Core.Forum forum = this.GetRepository<Core.Forum>().Read(id);

			IEnumerable<ForumAccess> masks = this.GetRepository<ForumAccess>().ReadMany(new ForumAccessSpecifications.SpecificForum(forum));
			return this.CustomJson(new { Masks = masks.Select(m => new { Id = m.Id, Group = m.Group.Id, AccessMask = m.AccessMask.Id }) });
		}
	}
}